package cn.hl.org.service.impl;

import cn.hl.basic.service.impl.BaseServiceImpl;
import cn.hl.org.domain.Department;
import cn.hl.org.mapper.DepartmentMapper;
import cn.hl.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        List<Department> all = departmentMapper.findAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department: all) {
            map.put(department.getId(), department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department: all) {
            if (department.getParent_id() == null) {
                deptTree.add(department);
            } else {
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                if (parentDepartment != null) {
                parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
